﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Forms.SatinAlma;
using ConfExpert.Utility;
using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace ConfExpert.Forms.Satinalma
{
    public partial class CK : XForm
    {
        int CKBatchId;
        double FAO_A, FAO_G;
        DataSet dsData = null;

        public CK(int ckKBatchId)
        {
            InitializeComponent();

            this.CKBatchId = ckKBatchId;
            this.Text += "- " + AppSession.Lookups.CKBatch.FindByCKBatchId(CKBatchId).Notes;
        }

        void CK_Load(object sender, EventArgs e)
        {
            BindData();
            ceA.EditValueChanged += ceA_EditValueChanged;
            ceG.EditValueChanged += ceG_EditValueChanged;
            btnSave.ItemClick += btnSave_ItemClick;
            btnRefresh.ItemClick += btnRefresh_ItemClick;
            btnTakip.ItemClick += btnTakip_ItemClick;
            btnTakipM.ItemClick += btnTakipM_ItemClick;
            btnMuadilAra.ItemClick += btnMuadilAra_ItemClick;
            gv.RowCellStyle += gv_RowCellStyle;
            gv.FocusedRowChanged += gv_FocusedRowChanged;
            gv.ShowingEditor += gv_ShowingEditor;
            GridManager.GetManager(gv).Pasting += CK_Pasting;
            gv.DoubleClick += gv_DoubleClick;

            btnSave.Enabled = ytk(83);
            btnTakipM.Visibility = ytk(82) ? BarItemVisibility.Always : BarItemVisibility.Never;

            gv.SetToolTip(
                     "QtyA: Net AnaBeden ihtiyacı",
                     "QtyAx: Fazla Alım Oranı eklenmiş AnaBeden ihtiyacı",
                     "QtyG: Net Garni ihtiyacı",
                     "QtyGx: Fazla Alım Oranı eklenmiş Garni ihtiyacı",
                     "QtyRequired: Fazla Alım Oranı eklenmiş Toplam ihtiyaç",
                     "QtyAyrilan: Deponun kesin olarak ayırdığı toplar",
                     "Ax: Kalan üretim için AnaBeden ihtiyacı",
                     "Gx: Kalan üretim için Garni ihtiyacı",
                     "Qta: Kalan üretim için Toplam ihtiyaç",
                     "QtyBUIO: Depodan kullanılacak kısım",
                     "OrderMts: Sipariş edilen miktar");

            gv.OptionsView.RowAutoHeight = false;

            gv.MakeColumnInvisible("QtyA", "QtyG", "idx", "CKBatchId");

            gv.FormatAsNumber(0, "QtyA", "QtyG", "QtyAx", "QtyGx", "QtyRequired", "QtyAyrilan", "Ax", "Gx", "Qta", "QtyBUIO", "OrderMts");
            gv.FormatAsNumber(2, "Fiyat");

            gv.SetCaptions("QtyA:Orj. Beden Net", "QtyG:Orj. Garni Net",
                "QtyAx:Orj. FAO Beden", "QtyGx:Orj. FAO Garni", "QtyRequired:Orj. FAO Toplam",
                "Ax:G. FAO Beden", "Gx:G. FAO Garni", "Qta:G. FAO Toplam",
                "Cust7Order:Adet", "EskiHLNo:HLNo", "Nr:#", "OrderMts:EksikMt"
                );

            gv.AddSummary("QtyA", "QtyG", "QtyAx", "QtyGx", "QtyRequired", "QtyAyrilan", "Ax", "Gx", "Qta", "QtyBUIO", "OrderMts", "Fiyat");

            foreach (string str in "Konstruksiyon;Durum;UreticiId;KaliteGrup".Split(';'))
                gv.Columns[str].OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;

            gv.SortInfo.ClearAndAddRange(new GridColumnSortInfo[] { new GridColumnSortInfo(gv.Columns["Nr"], ColumnSortOrder.Ascending) });

            RestoreLayout();

            if (dsData.Tables["CikisPartisiLines"].Rows.Count > 0)
            {
                gv.Columns["Ax"].VisibleIndex = gv.Columns["QtyAyrilan"].VisibleIndex;
                gv.Columns["Gx"].VisibleIndex = gv.Columns["QtyAyrilan"].VisibleIndex;
                gv.Columns["Qta"].VisibleIndex = gv.Columns["QtyAyrilan"].VisibleIndex;
            }
            else
                gv.MakeColumnInvisible("Ax", "Gx", "Qta");

            splitter.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;

            cellStyler.Visible = false;

            gv.BestFitColumns();
        }

        void CK_Pasting(int rowHandle, GridColumn column, object val, CancelEventArgs ce)
        {
            ce.Cancel = AllowEdit();
        }

        void btnRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            BindData();
            gv.BestFitColumns();
        }

        void BindData()
        {
            dsData = ExecuteDataSet("GetCK3", CKBatchId);
            dsData.Tables[0].TableName = "CK";
            dsData.Tables[1].TableName = "Ayrilan";
            dsData.Tables[2].TableName = "Layout";
            dsData.Tables[3].TableName = "GPBedenGarni";
            dsData.Tables[4].TableName = "CurrentNeed";
            dsData.Tables[5].TableName = "CikisPartisiLines";

            dsData.Relations.Add(new DataRelation("FK_CK_GPBedenGarni_ProductId", dsData.Tables["GpBedenGarni"].Columns["ProductId"], dsData.Tables["CK"].Columns["ProductId"]));
            dsData.Relations.Add(new DataRelation("FK_CurrentNeed_CK_idx", dsData.Tables["CK"].Columns["idx"], dsData.Tables["CurrentNeed"].Columns["idx"]));
            dsData.Relations.Add(new DataRelation("FK_Ayrilan_CK_idx", dsData.Tables["CK"].Columns["idx"], dsData.Tables["Ayrilan"].Columns["idx"]));

            dsData.Tables["CK"].Columns.Add("Ax", typeof(decimal), "SUM(Child(FK_CurrentNeed_CK_idx).A)*(1000+" + (FAO_A * 10).ToString() + ")/1000");
            dsData.Tables["CK"].Columns.Add("Gx", typeof(decimal), "SUM(Child(FK_CurrentNeed_CK_idx).G)*(1000+" + (FAO_G * 10).ToString() + ")/1000");
            dsData.Tables["CK"].Columns.Add("Qta", typeof(decimal), "ISNULL(Ax,0) + ISNULL(Gx,0)");

            dsData.Tables["CK"].Columns["QtyAx"].Expression = "IsNull(QtyA,0)*(1000+" + (FAO_A * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["QtyGx"].Expression = "IsNull(QtyG,0)*(1000+" + (FAO_G * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["QtyRequired"].Expression = "ISNULL(QtyAx,0) + ISNULL(QtyGx,0)";
            dsData.Tables["CK"].Columns["QtyAyrilan"].Expression = "SUM(Child(FK_Ayrilan_CK_idx).Qty)";

            dsData.Tables["CK"].Columns["Ax"].Expression = "SUM(Child(FK_CurrentNeed_CK_idx).A)*(1000+" + (FAO_A * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["Gx"].Expression = "SUM(Child(FK_CurrentNeed_CK_idx).G)*(1000+" + (FAO_G * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["Qta"].Expression = "ISNULL(Ax,0) + ISNULL(Gx,0)";

            dsData.Tables["CK"].Columns["OrderMts"].Expression = "Qta+ISNULL(QtyBUIO,0)-ISNULL(QtyAyrilan,0)";

            dsData.Tables["CK"].Columns["Nr"].Expression = "Parent(FK_CK_GPBedenGarni_ProductId).Nr";
            dsData.Tables["CK"].Columns["BedenGarni"].Expression = "Parent(FK_CK_GPBedenGarni_ProductId).Arts";

            if (gv.DataSource == null)
                gv.Init(dsData.Tables["CK"]);
            else
                gv.RefreshDataSource(dsData);

            SetInfo();

            gv.RefreshData();
            gv.PostEditor();
        }

        void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ytk(81))
                SaveLayout();

            gv.Update("idx,Cust7Order,CustomerNotes,QtyAyrilan,QtyBUIO,Durum,Durum2,GecilenSiparis,UreticiId,KumasDeptNot,KompozisyonId,Konstruksiyon,EskiHLNo,PONr,SipTarihi,TerminETA,Fiyat,DvzId,EskiKod,KaliteGrup", "CK");
        }

        void btnMuadilAra_ItemClick(object sender, ItemClickEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            Dictionary<int, List<int>> muadil = new Dictionary<int, List<int>>();
            Dictionary<int, int> ihtiyac = new Dictionary<int, int>();
            foreach (DataRow dr in dsData.Tables["CK"].Select("OrderMts>0"))
            {
                int eksik = (int)dr["ProductId"];
                ihtiyac[eksik] = (int)dr["OrderMts"];

                List<int> result = GetSimilarsTopN(eksik, 80);

                muadil.Add(eksik, new List<int>());
                foreach (int i in result)
                    muadil[eksik].Add(i);
            }
            Cursor = Cursors.Default;

            AppSession.MainForm.ShowMdiChildForm(typeof(BenzerRenkler2), muadil, ihtiyac);
        }

        void btnTakipM_ItemClick(object sender, ItemClickEventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(GPGelenM), CKBatchId, FAO_A, FAO_G);
        }

        void btnTakip_ItemClick(object sender, ItemClickEventArgs e)
        {
            AppSession.MainForm.ShowMdiChildForm(typeof(GPGelen), CKBatchId, FAO_A, FAO_G);
        }

        void gv_DoubleClick(object sender, EventArgs e)
        {
            if (gv.FocusedColumn.FieldName == "Scan")
                Goster(gv.GetFocusedDataRow()["ProductId"].ToInt());
        }

        void gv_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = AllowEdit();
        }

        private bool AllowEdit()
        {
            bool allow = (gv.FocusedRowHandle >= 0 && (
            gv.FocusedColumn.FieldName == "ProductId" ||
            gv.FocusedColumn.FieldName == "PRO" ||
            gv.FocusedColumn.FieldName == "Descrizione" ||
            gv.FocusedColumn.FieldName == "QtyAx" ||
            gv.FocusedColumn.FieldName == "QtyGx"));
            return allow;
        }

        void ceG_EditValueChanged(object sender, EventArgs e)
        {
            FAO_G = intParse(ceG.EditValue);
            dsData.Tables["CK"].Columns["QtyGx"].Expression = "IsNull(QtyG,0)*(1000+" + (FAO_G * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["Gx"].Expression = "SUM(Child(FK_CurrentNeed_CK_idx).G)*(1000+" + (FAO_G * 10).ToString() + ")/1000";

            gv.RefreshData();
        }

        void ceA_EditValueChanged(object sender, EventArgs e)
        {
            FAO_A = intParse(ceA.EditValue);
            dsData.Tables["CK"].Columns["QtyAx"].Expression = "IsNull(QtyA,0)*(1000+" + (FAO_A * 10).ToString() + ")/1000";
            dsData.Tables["CK"].Columns["Ax"].Expression = "SUM(Child(FK_CurrentNeed_CK_idx).A)*(1000+" + (FAO_A * 10).ToString() + ")/1000";

            gv.RefreshData();
        }

        void gv_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            SetInfo();
        }

        void SetInfo()
        {
            txtInfo.Caption = gv.GetFocusedRowCellDisplayText("ProductId").ToStr() +
                (gv.GetFocusedRowCellDisplayText("Descrizione").ToStr() != string.Empty ? " | " + gv.GetFocusedRowCellDisplayText("Descrizione").ToStr() : string.Empty);
        }

        void gv_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            switch (e.Column.FieldName)
            {
                case "PRO": //-PRO
                case "ProductId":
                case "OrderMts":
                case "UreticiId":
                case "QtyRequired":
                case "Qta":
                case "QtyAyrilan":
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                    break;
            }


            if (gv.GetRowCellDisplayText(e.RowHandle, "Durum") == "YUKLENDI")
            {
                switch (e.Column.FieldName)
                {
                    case "Durum":
                        e.Appearance.ForeColor = Color.LimeGreen;
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }
            }
            else
                switch (e.Column.FieldName)
                {
                    case "OrderMts":
                        e.Appearance.ForeColor = Color.Firebrick;
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        break;
                }


            switch (e.Column.FieldName)
            {
                case "QtyAyrilan":
                    e.Appearance.BackColor = Color.Honeydew;
                    e.Appearance.ForeColor = Color.DarkOliveGreen;
                    break;
            }
        }

        void SaveLayout()
        {
            gv.EndEditing();
            MemoryStream ms = new MemoryStream();
            gv.SaveLayoutToStream(ms);

            ExecuteNonQuery("UpdCK", CKBatchId,
                Encoding.UTF8.GetString(ms.ToArray()),
                cellStyler.Style.ToString(), FAO_A, FAO_G);
        }

        void RestoreLayout()
        {
            if (dsData.Tables["Layout"].Rows[0]["SerializedLayout"] != DBNull.Value)
            {
                string layout = dsData.Tables["Layout"].Rows[0]["SerializedLayout"].ToStr();
                if (layout.Trim() == string.Empty)
                    return;

                if (layout.Substring(0, 1) == "?")
                    layout = layout.Substring(1);

                gc.ForceInitialize();
                gv.RestoreLayoutFromStream(
                    new MemoryStream(Encoding.UTF8.GetBytes(layout)));
            }

            //if (!dsData.Tables["Layout[0].IsSerializedFormatNull())
            //    cellStyler1.BindToGridView(gridView1, "idx", dsData.Tables["Layout[0].SerializedFormat);
            //else
            //    cellStyler1.BindToGridView(gridView1, "idx");

            if (dsData.Tables["Layout"].Rows[0]["FAO_A"] != DBNull.Value)
                ceA.EditValue = dsData.Tables["Layout"].Rows[0]["FAO_A"].ToDecimal();

            if (dsData.Tables["Layout"].Rows[0]["FAO_G"] != DBNull.Value)
                ceG.EditValue = dsData.Tables["Layout"].Rows[0]["FAO_G"].ToDecimal();
        }
    }
}